import numpy as np

def readTrack(filename):
	header = True
	headerFields = {}
	data = []
	
	for ln in open(filename).read().split("\n"):
		if(ln=="EST_Header_End"): 
			header = False
			numFrames = int(headerFields["NumFrames"])
		elif(header):
			h = ln.split(" ")
			headerFields[h[0]]=h[1]
		elif len(ln):
			d = ln.split(" ")
			a = float(d[0])
			b = int(d[1])
			c = float(d[2])
			data += [[a,b,c]]
	
	return headerFields,data
	
def getPitch(d0,d1,pos):
	if(pos[1]==1): #voiced
		p = pos[0]
		for i in range(0,len(d0)-1):
			p0 = d0[i]
			p1 = d0[i+1]
			if(p0[0]<=p and p1[0]>p):
				interp = (p1[0]-p)/(p1[0]-p0[0])
				return p0[2]*interp+p1[2]*(1-interp)
	return 0;
	
def calculate_windowed_waveform(x: np.ndarray, fs: int, f0: float, temporal_position: float) -> np.ndarray:
    half_window_length = int(fs / f0 + 0.5)
    base_index = np.arange(-half_window_length, half_window_length + 1)
    index = int(temporal_position * fs + 0.501) + 1.0 + base_index
    safe_index = np.minimum(len(x), np.maximum(1, index))
    safe_index = np.array(safe_index, dtype=np.int)
    
    #  wave segments and set of windows preparation
    segment = x[safe_index - 1]
    time_axis = base_index / fs
    window = 0.5 * (np.cos(np.pi * time_axis * f0)) + 0.5
 
    return window*segment,safe_index

def getImpulse(x,fs,f0,d1,p):
	for i in range(0,len(d1)-1):
		p0 = d1[i]
		p1 = d1[i+1]
		if(p0[0]<=p and p1[0]>p):
			interp = (p1[0]-p)/(p1[0]-p0[0])
			t0 = p0[0]
			t1 = p1[0]
			imp0,s0 = calculate_windowed_waveform(x,fs,f0,t0)
			imp1,s1 = calculate_windowed_waveform(x,fs,f0,t1)
			return imp0*interp+imp1*(1-interp)
	return None;
